//
//  ViewController.swift
//  mlz
//
//  Created by 吕凌 on 2018/4/3.
//  Copyright © 2018年 吕凌. All rights reserved.
//

import UIKit
import WeexSDK

class ViewController: UIViewController, UIGestureRecognizerDelegate {
    
    var weexInstance:WXSDKInstance?
    var weexView = UIView()
    var weexHeight:CGFloat?
    var top:CGFloat?
    var url:URL?
    var main:Bool = false

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        self.navigationController?.interactivePopGestureRecognizer?.delegate = self
        render()
        NotificationCenter.default.addObserver(self, selector:#selector(viewDidAppear), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
        NotificationCenter.default.addObserver(self, selector:#selector(viewDidDisappear), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    deinit {
        /*
         *http://stackoverflow.com/questions/31365097/can-i-print-function-type-in-swift
         *
         */
        print(#function)
        NotificationCenter.default.removeObserver(self)
        if weexInstance != nil {
            weexInstance!.destroy()
        }
        self.navigationController?.interactivePopGestureRecognizer?.delegate = nil;
    }
    
    func render() {
        if weexInstance != nil {
            weexInstance!.destroy()
        }
        weak var weakSelf = self
        weexInstance = WXSDKInstance()
        weexInstance!.viewController = weakSelf
        let width = self.view.frame.size.width
        weexInstance!.frame = CGRect(x:0, y:0, width: width, height: self.view.frame.size.height)
        weexInstance?.onCreate = {
            (view:UIView?)-> Void in
            weakSelf!.weexView.removeFromSuperview()
            weakSelf!.weexView = view!;
            weakSelf!.view.addSubview((weakSelf?.weexView)!)
            UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, weakSelf!.weexView)
        }
        
        weexInstance?.onFailed = {
            (error:Error?)-> Void in
            print("faild at error: %@", error!)
            self.networkLostView.isHidden = false
        }
        
        weexInstance?.renderFinish = {
            (view:UIView?)-> Void in
            print("render finish")
        }
        
        weexInstance?.updateFinish = {
            (view:UIView?)-> Void in
            print("update finish")
        }
        
//        weexInstance!.render(with: url, options: ["bundleUrl":String.init(format: "file://%@/bundlejs/", Bundle.main.bundlePath)], data: nil)
        weexInstance!.render(with: url, options: ["bundleUrl":"http://192.168.18.119/lxk/"], data: nil)
    }
    
    private lazy var networkLostView: UIView = {
        let panel:UIView = UIView.init()
        panel.frame = CGRect(x:0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        panel.backgroundColor = UIColor.white
        let imageView:UIImageView = UIImageView(image:#imageLiteral(resourceName: "network_lost.png"))
        let imageWidth:CGFloat = 250;
        let imageHeight:CGFloat = 250;
        imageView.frame = CGRect(x:(UIScreen.main.bounds.width - imageWidth) / 2, y: (UIScreen.main.bounds.height - imageHeight) / 2 - 60, width:imageWidth, height:imageHeight)
        panel.addSubview(imageView)
        let tapGR = UITapGestureRecognizer(target: self, action: #selector(networkLostViewHandler))
        panel.addGestureRecognizer(tapGR)
        panel.isHidden = true
        panel.isUserInteractionEnabled = true
        self.view.addSubview(panel)
        return panel
    }()
    
    @objc func networkLostViewHandler(sender:UITapGestureRecognizer) {
        networkLostView.isHidden = true
        self.weexInstance?.reload(true)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        self.updateInstanceState(state: WXState.WeexInstanceDisappear)
        if((self.navigationController?.viewControllers.count)! >= 1) {
            self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true;
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.updateInstanceState(state: WXState.WeexInstanceAppear)
        if(self.navigationController?.viewControllers.count == 1) {
            self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false;
        }
    }

    private func updateInstanceState(state: WXState) {
        if(state == WXState.WeexInstanceAppear) {
            WXSDKManager.bridgeMgr().fireEvent(weexInstance?.instanceId, ref: WX_SDK_ROOT_REF, type: "viewappear", params: nil, domChanges: nil)
        } else {
            WXSDKManager.bridgeMgr().fireEvent(weexInstance?.instanceId, ref: WX_SDK_ROOT_REF, type: "viewdisappear", params: nil, domChanges: nil)
        }
    }
}

